package com.cloud.yangfeiself.util;

import com.alibaba.fastjson.JSON;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 *  web环境适用的工具类
 *
 * @author Yang Fei
 * @date 2021/3/9
 */
public class WebUtil {


    public static String getParam(String name){
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getParameter(name);
    }


    public static Map getParamMap(){
        Map<String, String[]> parameterMap = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest().getParameterMap();
        return parameterMap;
    }

    public static void responseJson(Object object){
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);

        try(ServletOutputStream outputStream=response.getOutputStream()) {
//            outputStream.print(new String(JSON.toJSONString(object).getBytes(), Charsets.ISO_8859_1));
            outputStream.write(JSON.toJSONString(object).getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String[] args) {
        System.out.println("ContentType.APPLICATION_JSON.toString() = " + MediaType.APPLICATION_JSON.toString());

    }
}
